import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# Load the dataset
url = "https://raw.githubusercontent.com/MicrosoftDocs/mslearn-introduction-to-machine-learning/main/Data/ml-basics/penguins.csv"
df = pd.read_csv(url)

# Print the first 5 rows of the dataset
print(df.head(5))

# Let's visualize the distribution of the penguins species with a bar plot in matplotlib
species_counts = df['Species'].value_counts()
plt.figure(figsize=(8, 5))
species_counts.plot(kind='bar', color=['#1f77b4', '#ff7f0e', '#2ca02c'])
plt.title('Distribution of Penguin Species')
plt.xlabel('Species')
plt.ylabel('Count')
plt.xticks(rotation=45)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

# Let's visualize with boxplots how the FlipperLength, CulmenLength and CulmenDepth are distributed for each species
# importing seaborn
plt.figure(figsize=(15, 5))

plt.subplot(1, 3, 1)
sns.boxplot(x='Species', y='FlipperLength', data=df)
plt.title('Flipper Length Distribution by Species')

plt.subplot(1, 3, 2)
sns.boxplot(x='Species', y='CulmenLength', data=df)
plt.title('Culmen Length Distribution by Species')

plt.subplot(1, 3, 3)
sns.boxplot(x='Species', y='CulmenDepth', data=df)
plt.title('Culmen Depth Distribution by Species')

plt.tight_layout()
plt.show()

# Show rows with missing values
print("Rows with missing values:\n", df[df.isnull().any(axis=1)])

# Drop rows with missing values
columns_to_fill = ['CulmenLength', 'CulmenDepth', 'FlipperLength']  # Columns to fill

for column in columns_to_fill:
    median_value = df[column].median()  # Calculate the median
    df[column].fillna(median_value, inplace=True)  # Drop rows with missing values

# Check if there are still missing values after filling
print("Rows with missing values after filling:\n", df[df.isnull().any(axis=1)])

# Let's prepare for training:
# 1. Split the data into features and labels
features = df[['CulmenLength', 'CulmenDepth', 'FlipperLength']]
labels = df['Species']

# 2. Split the data into training and test sets, with 30% of the data for testing
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.3, random_state=42)

# Create a multiclass logistic regression model
model = LogisticRegression(max_iter=200)

# Train the model
model.fit(X_train, y_train)

# Evaluate the model
# 1. Predict the labels of the test set
y_pred = model.predict(X_test)

# 2. Calculate the accuracy of the model
accuracy = accuracy_score(y_test, y_pred)
print(f"Model accuracy: {accuracy:.2f}")
